// var dbConfig = require('../util/dbconfig')

//随机验证码
function rand(min, max) {
	return Math.floor(Math.random() * (max - min)) + min
}
validatePhoneCode = [];
let sendCodeP = (phone) => {
	for (var item of validatePhoneCode) {
		if (phone == item.phone) {
			return true
		}
	}
	return false
}
let findCodeAndPhone = (phone, code) => {
	for (var item of validatePhoneCode) {
		if (phone == item.phone && code == item.code) {
			return 'login'
		}
	}
	return 'error'
}


//模拟验证码发送接口
sendCode = (req, res) => {
	let phone = req.body.phone;
	console.log(req)
	if (sendCodeP(phone)) {
		res.send({
			'code': 400,
			'msg': '已经发了验证码,稍后再发'
		})
	}
	let code = rand(1001, 9999);
	validatePhoneCode.push({
		'phone': phone,
		'code': code
	})
	console.log(validatePhoneCode)
	res.send({
		'code': 200,
		'mag': '发送成功'
	})
	console.log(code)
}

//验证码登录
codePhoneLogin = (req, res) => {
	
	let phone = req.body.phone;
	console.log(phone)
	let code = req.body.code;
	console.log(code)
	//验证手机号是否发送过验证码.
	if (sendCodeP(phone)) {
		//验证码手机号是否匹配
		let status = findCodeAndPhone(phone, code);
		console.log(status)
		if (status == 'login') {
			res.send({
				'code': 200,
				'msg': '登录成功'
			})
		} else if (status == 'error') {
			res.send({
				'code': 200,
				'msg': '登录失败'
			})
		}
	} else {
		res.send({
			'code': 400,
			'msg': '未发送验证码'
		})
	}
}



module.exports = {
	sendCode,
	codePhoneLogin
}
